import {EventBus} from "./eventbus.js";

export var Router = { //
    routes : {},  //存放路由的
    //添加路由
    addRoute(url, loader){
        this.routes[url] = loader;  //loader是一个函数
    },

    //无论如何都必须要加载+layout
    async navigate(){
        //获取localStorage中的用户信息
        //如果没有获取到用户的信息,则跳转到login页面

        if(!localStorage.getItem("user-info")){
            location.href="/ourmall-admin/login.html";
        }

        var module = await import("./components/+layout.js");
        var appDiv = document.getElementById("app");
        if(module && module.render){
            var html = module.render();
            if(html){
                appDiv.innerHTML = html;

                if(module.afterRender){
                    module.afterRender();
                }
            }else{
                EventBus.emit("route:404","<h1>404 Not Found</h1>");
            }
            EventBus.emit("component:rendered", module.name || "Unknown");
        }else{
            appDiv.innerHTML = "<h1>组件加载失败</h1>"
        }
    }
}